/*
 *所有关于WaitUpgradeDev类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*WaitUpgradeDevService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.RadarDevice.IRepositories;
using SqlSugar;
using System.Net;
using VOL.Core.DbContext;
using VOL.Entity.DomainModels.Devices.Dto;
using VOL.Entity.DomainModels.Devices.MongoDbModels;
using VOL.Entity.DomainModels.UpgradeManager.Dto;
using VOL.Core.DBManager;
using VOL.Core.ManageUser;
using Newtonsoft.Json;
using System.Collections.Generic;
using VOL.Core.Configuration;
using VolPro.Core.Extensions;
using System.Text;

namespace VOL.RadarDevice.Services
{
    public partial class WaitUpgradeDevService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWaitUpgradeDevRepository _repository;//访问数据库
        private readonly IUpgradeFileManagerRepository _repositoryUpgradeFileManager;//访问数据库
        private readonly IdeviceShareRepository _repositorySharp;//访问数据库
        WebResponseContent webResponse = new WebResponseContent();

        [ActivatorUtilitiesConstructor]
        public WaitUpgradeDevService(
            IWaitUpgradeDevRepository dbRepository,
            IUpgradeFileManagerRepository dbRepository2,
            IdeviceShareRepository repositorySharp,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _repositorySharp = repositorySharp;
            _repositoryUpgradeFileManager = dbRepository2;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public override PageGridData<WaitUpgradeDev> GetPageData(PageDataOptions options)
        {
            var deviceNo = "";
            var uType = -1;
            DateTime? startTime = null;
            DateTime? endTime = null;

            var listWhere = JsonConvert.DeserializeObject<List<OptionWheres>>(options.Wheres);
            foreach (var item in listWhere)
            {
                if (item.name == "deviceNo")
                    deviceNo = item.value;
                else if (item.name == "uType" && !string.IsNullOrWhiteSpace(item.value))
                    uType = int.Parse(item.value);
                else if (item.name == "createTime" && item.displayType == "thanorequal")
                    startTime = DateTime.Parse(item.value);
                else if (item.name == "createTime" && item.displayType == "lessorequal")
                    endTime = DateTime.Parse(item.value);
            }

            int pageSize = options.Rows; // 每页显示的数量
            int pageIndex = options.Page; // 当前页码
            string sort = options.Sort;

            var querys = repository.FindAsIQueryable(r => 1 == 1).WhereIF(startTime.HasValue, m => m.createTime >= startTime.Value)
                .WhereIF(endTime.HasValue, m => m.createTime <= endTime.Value)
                .WhereIF(!string.IsNullOrWhiteSpace(deviceNo), d => d.deviceNo.Contains(deviceNo))
                .WhereIF(uType != -1, d => d.uType == uType);

            var allowIds = AppSetting.QueryAllDeviceUserIds;
            if (!string.IsNullOrWhiteSpace(allowIds))
            {
                var userId = UserContext.Current.UserId;
                var strIds = allowIds.Split(',');
                var ids = Array.ConvertAll(strIds, int.Parse);
                if (!ids.Contains(userId))
                {
                    var sharpModels = _repositorySharp.FindAsIQueryable(r => 1 == 1).ToList();
                    List<deviceShare> shares = new List<deviceShare>();
                    foreach (var sharpModel in sharpModels)
                    {
                        var userIds = sharpModel.shareUserIds.Split(",");
                        if (userIds.Contains(userId.ToString()))
                        {
                            shares.Add(sharpModel);
                        }
                    }
                    var deviceIdList = shares.Select(r => r.deviceId).ToList();
                    querys = querys.Where(d => d.CreateId == userId || deviceIdList.Contains(d.deviceId));
                }
            }
            var dtos = querys;
            if (options.Order == "desc")
                dtos = querys.OrderByDescending(d => d.createTime).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            else
                dtos = querys.OrderBy(d => d.createTime).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            PageGridData<WaitUpgradeDev> pageGridData = new PageGridData<WaitUpgradeDev>();
            var models = dtos.ToList();

            pageGridData.rows = models;
            pageGridData.total = querys.ToList().Count;

            GetPageDataOnExecuted?.Invoke(pageGridData);
            return pageGridData;
        }
        /// <summary>
        /// 请求升级指令缓存
        /// </summary>
        /// <param name="RequestUpgradeDto">请求参数</param>
        /// <returns></returns>
        public async Task<WebResponseContent> RequestUpgrade(RequestUpgradeDto dto)
        {
            if (string.IsNullOrWhiteSpace(dto.deviceNo) || string.IsNullOrWhiteSpace(dto.id))
            {
                return webResponse.Error("请选择升级设备！");
            }

            var fEntity = await _repositoryUpgradeFileManager.FindAsIQueryable(f => f.uType == dto.uType).OrderByDescending(f => f.createTime).FirstOrDefaultAsync();
            if (fEntity == null)
            {
                return webResponse.Error("请先上传升级文件！");
            }
            var entity = await _repository.FindAsIQueryable(r => r.deviceNo == dto.deviceNo && r.uType == dto.uType).OrderByDescending(r => r.createTime).FirstOrDefaultAsync();
            if (entity != null)
            {
                return webResponse.Error("已有升级任务，如想重新升级请先删除原升级任务！");
            }
            var userId = UserContext.Current.UserId;
            var user = UserContext.Current.GetUserInfo(userId);
            WaitUpgradeDev model = new WaitUpgradeDev()
            {
                uType = dto.uType,
                deviceId = Guid.Parse(dto.id),
                deviceNo = dto.deviceNo,
                createTime = DateTime.Now,
                CreateId = userId,
                Creator = user.UserTrueName
            };
            _repository.Add(model, true);
            return webResponse.OK("已添加升级任务，请等待后台升级!");
        }
        /// <summary>
        /// 删除(只有一条)
        /// </summary>
        /// <param name="keys">删除的行的主键</param>
        /// <param name="delList">删除时是否将明细也删除</param>
        /// <returns></returns>
        public override WebResponseContent Del(object[] keys, bool delList = true)
        {
            if (keys.Length < 0)
            {
                webResponse.Error("请选择删除的数据");
            }
            int[] ints = new int[keys.Length];

            for (int i = 0; i < keys.Length; i++)
            {
                ints[i] = int.Parse(keys[i].ToString());
            }
            var modelList = _repository.FindAsIQueryable(d=> ints.ToList().Contains(d.id)).ToList();
            foreach(var model in modelList)
            {
                var url = AppSetting.TcpServiceApiUrl + "Radar/api/CancelUpgrade?deviceNo=" + model.deviceNo;
                var resStr = HttpGet(url).Result;
                _repository.Delete(model, true);
            }
            return webResponse.OK();
        }
        #region HTTP请求
        /// <summary>
        /// http Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public async Task<string> HttpGet(string url)
        {
            string resStr = "";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    // 发送GET请求
                    HttpResponseMessage response = await client.GetAsync(url);
                    // 确保请求成功
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容作为字符串
                    resStr = await response.Content.ReadAsStringAsync();
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }
            return resStr;
        }
        /// <summary>
        /// Http Post请求(参数Json)
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="param">请求参数(json)</param>
        /// <returns></returns>
        public async Task<string> HttpPost(string url, string param)
        {
            string resStr = "";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    if (!string.IsNullOrEmpty(param))
                    {
                        // 将JSON字符串转换为HttpContent对象，并设置Content-Type为application/json
                        HttpContent content = new StringContent(param, Encoding.UTF8, "application/json");
                        // 发送POST请求
                        HttpResponseMessage response = await client.PostAsync(url, content);
                        // 确保请求成功
                        response.EnsureSuccessStatusCode();
                        resStr = await response.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        HttpResponseMessage response = await client.PostAsync(url, null);
                        // 确保请求成功
                        response.EnsureSuccessStatusCode();
                        // 读取响应内容
                        resStr = await response.Content.ReadAsStringAsync();
                    }
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }
            return resStr;
        }
        #endregion HTTP请求
    }
}
